package com.cloneoner.test.slider.view
{
	import flash.display.Bitmap;
	import flash.geom.Rectangle;
	import flash.display.DisplayObject;
	import flash.net.URLRequest;
	import flash.events.Event;

	import fr.digitas.flowearth.command.IBatchable;
	import fr.digitas.flowearth.net.BatchLoaderItem;

	import com.cloneoner.test.slider.data.ItemData;

	import flash.display.Graphics;
	import flash.display.Sprite;


	/**
	 * @author Thibault Loup
	 */
	public class ItemImg extends Sprite
	{

		// __________________________________________________________
		// -										 	  CONSTRUCTOR
		public function ItemImg(pData : ItemData)
		{
			_data = pData;

			_build();
		}


		// __________________________________________________________
		// -										  PUBLICS METHODS
		public function getLoadables() : IBatchable
		{
			return _bli;
		}

		public function dispose() : void
		{
			_killLoadables();

			if ( _content && _content is Bitmap)
			{
				Bitmap(_content).bitmapData.dispose();
			}
		}

		override public function get width() : Number
		{
			return _data.width;
		}


		override public function get height() : Number
		{
			return _data.height;
		}


		// __________________________________________________________
		// -										 		   EVENTS

		private function _onLoaded(event : Event) : void
		{
			_content = _bli.loader.content;

			_content.x = int((_data.width - _content.width) / 2);
			_content.y = int((_data.height - _content.height) / 2);
			addChild(_content);
		}

		// __________________________________________________________
		// -										 PRIVATES METHODS

		private function _build() : void
		{
			_bli = new BatchLoaderItem(new URLRequest(_data.src));
			_bli.addEventListener(Event.COMPLETE, _onLoaded);

			_drawBg(this.graphics);

			_throbber = new Throbber();
			_throbber.x = int(_data.width / 2);
			_throbber.y = int(_data.height / 2);
			addChild(_throbber);

			mouseEnabled = true;
			mouseChildren = false;
			
			this.scrollRect = new Rectangle(0, 0, _data.width, _data.height);
		}

		private function _drawBg(pGraphics : Graphics) : void
		{
			with(pGraphics)
			{
				clear();
				beginFill(_data.color);
				drawRect(0, 0, _data.width, _data.height);
			}
		}

		private function _killLoadables() : void
		{
			if ( !_bli ) return;

			_bli.removeEventListener(Event.COMPLETE, _onLoaded);
			_bli.dispose();
			_bli = null;
		}



		/* CONTENT */
		private var _throbber : Throbber;
		private var _content : DisplayObject;

		/* VAR */
		private var _data : ItemData;
		private var _bli : BatchLoaderItem;
	}
}